#!/usr/bin/env python
#coding=utf-8
# Description: show csd_agent version
# Author: carl

import subprocess
import sys
import os

# 查看版本信息的命令.
SOFT_NAME = "csd"
VERSION_CMD = ["/opt/fonsview/NE/csd/bin/version.sh"]

try:
    from subprocess import DEVNULL # py3k
except ImportError:
    DEVNULL = open(os.devnull, 'wb')

# Run the command.
def get_output(command):
    try:
        output = subprocess.check_output(command, stderr=DEVNULL)
    except subprocess.CalledProcessError as e:
        return None
    return output.decode()

# Print metrics in Prometheus format.
def print_version(metric, version):
    print("# HELP %s show version metric for %s" % (metric, metric))
    print("# TYPE %s gauge" % (metric))
    print("%s{version=\"%s\"} 1" % (metric, version.strip()))

# 检查路径是否存在
def check_dir(SOFT_NAME):
    SOFT_PATH = os.environ.get(SOFT_NAME.upper() + '_PATH', "path_not_exist")
    if not os.path.exists(SOFT_PATH):
        sys.exit(1)
    if not os.path.isfile(VERSION_CMD[0]):
        sys.exit(1)

# Main function
def main():
    check_dir(SOFT_NAME)
    version = get_output(VERSION_CMD).strip()
    if not version:
        version = "version_get_fail"
    metric = os.path.basename(__file__)
    print_version(metric, version)

# Go go go!
if __name__ == "__main__":
    main()
